package entity

import (
	"strings"
	"time"

	"github.com/google/uuid"
	"github.com/jinzhu/gorm"
)

type ProjectGroup struct {
	ID               string    `gorm:"column:id" json:"id"`
	Name             string    `gorm:"column:name" json:"name"`
	Description      string    `gorm:"column:description" json:"description"`
	Sort             int       `gorm:"column:sort" json:"sort"`
	IsShow           BitBool   `gorm:"column:is_show" json:"isShow"`
	ProjectCount     int       `gorm:"column:project_count" json:"projectCount"`
	CreatedTime      time.Time `gorm:"column:created_time" json:"createdTime"`
	LastModifiedTime time.Time `gorm:"column:last_modified_time" json:"lastModifiedTime"`
	IsDefaultGroup   bool      `gorm:"-" json:"isDefaultGroup"`
}

func (*ProjectGroup) TableName() string {
	return "project_group"
}

func (p *ProjectGroup) AfterFind(tx *gorm.DB) (err error) {
	// 判断是否是默认Group
	if p.ID == "1" {
		p.IsDefaultGroup = true
	} else {
		p.IsDefaultGroup = false
	}
	return
}

func (p *ProjectGroup) BeforeCreate(tx *gorm.DB) (err error) {
	p.ID = strings.ReplaceAll(uuid.New().String(), "-", "")
	now := time.Now()
	p.CreatedTime = now
	p.LastModifiedTime = now

	// 找到最大的sort
	var maxSort int
	rows, err := tx.Raw("select max(sort) from project_group").Rows()
	if err != nil {
		return err
	}
	defer rows.Close()
	for rows.Next() {
		rows.Scan(&maxSort)
	}
	p.Sort = maxSort + 1
	return
}
